<?php
/**
 * User: dimka3210
 * Date: 21.04.14
 * Time: 20:51
 */

define('PORTAL_HTML', 'portal_html');

/**
 * @return string
 */
function get_stream_html()
{
    global $bb_cfg;

    if (($html = CACHE('bb_cache')->get(PORTAL_HTML)) && $bb_cfg['portal']['cache']) {
        return $html;
    }
    $colspan = $bb_cfg['portal']['items_in_line'];
    $html = '<table class="forums">
		<tr class="row3">
			<th colspan="'.$colspan.'">Портал новинок</th>
		</tr>
		<tr>';
    $rows = get_last_topics();
    for ($i = 0; $i < count($rows); $i++) {
        $row = $rows[$i];
        if ($i > 0 && ($i % $bb_cfg['portal']['items_in_line']) == 0) {
            $html .= '</tr><tr>';
        }
        $html .= get_item($row);
    }
    $html .= '</tr></table>';
    CACHE('bb_cache')->set(PORTAL_HTML, $html, 60);
    return $html;
}


/**
 * @return array
 */
function get_last_topics()
{
    global $bb_cfg;
    $tor_approved = TOR_APPROVED;
    $tor_doubtful = TOR_DOUBTFUL;

    $sql = <<<SQL
    SELECT t.topic_id, t.topic_title, t.topic_time, p.post_id,
           pt.post_text, tor.tor_status, tor.size, u.user_id,
           u.username, u.user_rank, ph.post_html
    FROM bb_topics t, bb_posts p, bb_posts_text pt, bb_bt_torrents tor, bb_users u, bb_posts_html ph
    WHERE p.post_id=t.topic_first_post_id
        AND pt.post_id=p.post_id
        AND tor.topic_id=t.topic_id
        AND tor.tor_status IN ($tor_approved, $tor_doubtful)
        AND u.user_id=t.topic_poster
        AND ph.post_id=p.post_id
    ORDER BY t.topic_id DESC
    LIMIT {$bb_cfg['portal']['items_limit']}
SQL;

    return DB()->fetch_rowset($sql);
}

/**
 * @param $row
 * @return string
 */
function get_item($row)
{
    global $bb_cfg;

    $data = date("d-m-Y", $row['topic_time']);
    $img = get_poster_url_from_text($row['post_text']);
    $size = humn_size($row['size']);
    $height = $bb_cfg['portal']['item_height'];
    $status = get_status_name($row['tor_status']);
    $author = profile_url(array('username' => $row['username'], 'user_rank' => $row['user_rank']));

    return <<<HTML
    <td>
        <div style="background: url($img) no-repeat center center;background-size: cover; height: {$height}px" class="portal-item">
            <div class="fancy-avatar" href="{$img}" title="{$row['topic_title']}"></div>
            <div class="hint">
                <b><a class="link" href="/viewtopic.php?t={$row['topic_id']}">{$row['topic_title']}</a></b><br />
                <b>Автор:</b> {$author}<br>
                <b>Размещено:</b> {$data}<br>
                <b>Размер: {$size}</b><br>
                <b>Статус:</b> {$status}<br>
            </div>
        </div>
    </td>
HTML;
}

/**
 * @param string $html
 * @return string
 */
function get_poster_url_from_text($html)
{
    $image_url = parse_url_from_text($html);
    if (!$image_url) {
        return "/templates/default/images/noposter.jpg";
    }
    return $image_url;
}

/**
 * @param $regexp
 * @param $text
 * @return bool
 */
function find_by_regexp($regexp, $text)
{
    preg_match($regexp, $text, $matches);
    if (isset($matches[1])) {
        return $matches[1];
    }
    return false;
}

/**
 * @param $text
 * @return bool|string
 */
function parse_url_from_text($text)
{
    /**
     * Этот массив является ещё и настройкой приоритета.
     * Сначала ищем постер, потом картинку с правым выравниванием,
     * потом просто картинку, потом с левым выравниванием.
     * Если нужно изменить этот порядок, то просто строки меняем местами.
     */
    $regexp = array(
        "#\[poster\]([^[]*)\[\/poster\]#msi",
        "#\[img=right\]([^[]*)\[\/img\]#msi",
        "#\[img\]([^[]*)\[\/img\]#msi",
        "#\[img=left\]([^[]*)\[\/img\]#msi"
    );

    foreach ($regexp as $exp) {
        if ($link = find_by_regexp($exp, $text)) {
            return $link;
        }
    }

    return false;
}

/**
 * @param $status
 * @return string
 */
function get_status_name($status)
{
    global $lang;
    $html = '';
    switch (intval($status)) {
        case TOR_APPROVED:
            $html = '<span class="tor-icon tor-approved">√</span>';
            break;
        case TOR_DOUBTFUL:
            $html = '<span class="tor-icon tor-approved">#</span>';
            break;
    }
    return $html . ' <b>' . $lang['TOR_STATUS_NAME'][$status] . '</b>';
}